import { bindable, containerless } from 'aurelia-framework';

@containerless
export class EmFileUpload {

    files = [];

    /**
     * 当视图被附加到DOM中时被调用
     */
    attached() {

        let _this = this;
        $(this.uploadRef).children().andSelf().dropzone({
            url: "/admin/task/attachment/upload",
            paramName: 'file',
            clickable: true,
            dictDefaultMessage: '',
            maxFilesize: 10,
            addRemoveLinks: true,
            previewsContainer: this.previewRef,
            // previewTemplate: this.previewTemplateRef.innerHTML,
            dictCancelUpload: '取消上传',
            dictCancelUploadConfirmation: '确定要取消上传吗?',
            dictFileTooBig: '文件过大({{filesize}}M),最大限制:{{maxFilesize}}M',
            dictRemoveFile: '移除文件',
            init: function() {
                _this.dropzone = this;
                this.on("sending", function(file, xhr, formData) {
                    formData.append('toType', "Task");
                });
                this.on("success", function(file, data) {
                    if (data.success) {
                        _this.files.push(...data.data);
                    } else {
                        toastr.error(data.data, '上传失败!');
                    }

                });
                this.on("error", function(file, errorMessage, xhr) {
                    toastr.error(errorMessage, '上传失败!');
                });
                // this.on("complete", function(file) {
                //     // this.removeFile(file);
                // });
                this.on("removedfile", function(file) {
                    _this.files = _.reject(_this.files, { file: file });
                });
            }
        });
    }

    clear() {
        this.files = [];
        this.dropzone && this.dropzone.removeAllFiles();
    }
}
